package org.lansir.af.ui;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.lansir.af.R;
import org.lansir.af.database.DataRowActivity;
import org.lansir.af.database.DataTable;
import org.lansir.af.gtalk.service.Contact;
import org.lansir.af.gtalk.service.Message;
import org.lansir.af.gtalk.service.aidl.IChat;
import org.lansir.af.gtalk.service.aidl.IChatManager;
import org.lansir.af.gtalk.service.aidl.IXmppFacade;
import org.lansir.af.model.ActivityMessageItem;
import org.lansir.af.util.RepeatData;
import org.lansir.af.util.Utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityReceiveDialog extends CommonActivity {

	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("org.lansir.af", "org.lansir.af.gtalk.GtalkService"));
	}
	private GtalkServiceConnection mServiceConn = new GtalkServiceConnection();
	private IXmppFacade mXmppFacade;
	private IChatManager mChatManager;
	private boolean mBinded = false;

	private TextView informFromText;
	private TextView informContent;
	private Button btnSave;
	private Button btnClose;
	private String sMessage;
	private String sName;
	private long lNewRowId;
	private String sContent;
	private String sPlace;
	private int iYear, iMonth, iDay, iHour, iMinute;
	private int iRingmode;
	private boolean bAlarm;
	private String sRepeat;

	private DataRowActivity dataRowActivity = null;
	private DataTable dataTableActivity = null;

	private ActivityMessageItem smsMessageItem;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		getIntentDataFromBundle();
		init(R.layout.activity_receive_dialog);

	}

	@Override
	protected void onPause() {
		if (mBinded) {
			unbindService(mServiceConn);
			mBinded = false;
		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (!mBinded) {
			mBinded = bindService(SERVICE_INTENT, mServiceConn, Context.BIND_AUTO_CREATE);
		}
	}

	private void getIntentDataFromBundle() {
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			smsMessageItem = (ActivityMessageItem) bundle.getParcelable("MessageItem");
			sMessage = smsMessageItem.getBody();
			sName = smsMessageItem.getContact().getName();
			// sMessage = Utils.sMessage;

			Utils.sMessage = "";
			bundle.clear();
		}

	}

	private void sendMessageFeedback(Contact contact, String msgContent) {
		// TODO currently support gtalk
		if (smsMessageItem.getType() == ActivityMessageItem.MsgType.OTHER) {

			IChat chat;
			try {
				chat = mChatManager.getChat(contact);
				if (chat == null) {
					chat = mChatManager.createChat(contact, null);
				}
				Message msgToSend = new Message(contact.getJID(), Message.MSG_TYPE_CHAT);
				msgToSend.setBody(msgContent);
				chat.sendMessage(msgToSend);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	@Override
	protected void initViews() {
		utils = new Utils(this);
		dataRowActivity = new DataRowActivity(userdb);
		dataTableActivity = new DataTable(dataRowActivity);
		btnSave = (Button) findViewById(R.id.btnaddinformdialogOK);
		btnClose = (Button) findViewById(R.id.btnaddinformdialogCancel);
		informFromText = (TextView) findViewById(R.id.addinformFrom);
		informContent = (TextView) findViewById(R.id.addinformContent);

		sMessage = sMessage.replace("[活动精灵]", "");
		sMessage = sMessage.substring(0, sMessage.lastIndexOf("请按格式"));
		informFromText.setText("来自：" + sName);
		informContent.setText(sMessage);

		btnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i("inform", "save data");
				saveData();
				String sReply = ActivityReceiveDialog.this.lNewRowId + "_是";
				sendMessageFeedback(smsMessageItem.getContact(), sReply);
				// utils
				// .showConfirmDialog("是否参加本活动", saveListener,
				// cancelListener);
				finish();
				Log.i("inform", "save data OK");
				// TODO 当保存时，通知管理员要参加活动
				// mNM.cancel(LocationReminder.iNotifyID2);

			}

		});

		btnClose.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String sReply = ActivityReceiveDialog.this.lNewRowId + "_否";
				sendMessageFeedback(smsMessageItem.getContact(), sReply);
				finish();

			}

		});
	}

	@Override
	protected void initStates() {

	}

	public void saveData() {
		// check date if no repeat
		initContent();
		dataRowActivity.setSubject(this.sContent);
		dataRowActivity.setLocation(this.sPlace);
		Calendar calDate = Calendar.getInstance();
		calDate.set(this.iYear, this.iMonth, this.iDay, this.iHour, this.iMinute, 0);
		if (calDate.getTimeInMillis() < System.currentTimeMillis()) {
			Log.v("ActivityFairy", "less");
			Toast.makeText(this.getApplicationContext(), "当前活动已经过期!", 500).show();
			return;
		}
		Log.v("ActivityFairy", "more");
		dataRowActivity.setStartDate(calDate);

		dataRowActivity.setAlarm(this.bAlarm);

		dataRowActivity.setRingerMode(this.iRingmode);

		dataRowActivity.setOrganizer(this.sName);
		dataRowActivity.setSnooze(0);
		dataRowActivity.setSnoozeCount(0);
		setRepeat();
		dataRowActivity.setValuesForDataRow();
		dataTableActivity.updateData(true, -1);
		Toast.makeText(this.getApplicationContext(), "保存成功!", 500).show();

		// dataTableActivity.updateValues(lNewRowId);

	}

	private void setRepeat() {
		RepeatData rd = dataRowActivity.getRepeat();
		// set repeat type
		if ("无".equals(this.sRepeat)) {
			rd.setRepeatTypeAsInt(-1);
			rd.setEvery(0);
			rd.setEndOnDate(null);
			return;
		}

		this.sRepeat = this.sRepeat.replace("每", "");
		if (this.sRepeat.contains("年")) {
			rd.setRepeatTypeAsInt(4);
			this.sRepeat = this.sRepeat.replace("年", "");
		} else if (this.sRepeat.contains("月")) {
			rd.setRepeatTypeAsInt(3);
			this.sRepeat = this.sRepeat.replace("月", "");
		} else if (this.sRepeat.contains("周")) {
			rd.setRepeatTypeAsInt(2);
			this.sRepeat = this.sRepeat.replace("周", "");
		} else if (this.sRepeat.contains("日")) {
			rd.setRepeatTypeAsInt(1);
			this.sRepeat = this.sRepeat.replace("日", "");
		}
		String[] sTemp = this.sRepeat.split("直到");
		rd.setEvery(Integer.parseInt(sTemp[0].trim()));
		SimpleDateFormat dateFormatLong = new SimpleDateFormat("yyyy-MM-dd, EEEE");
		Date date;
		try {
			if (sTemp != null && sTemp.length == 2) {
				date = dateFormatLong.parse(sTemp[1]);
				Calendar cal = Calendar.getInstance();
				cal.setTime(date);
				rd.setEndOnDate(cal);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void initContent() {
		Log.v("ActivityFairy", sMessage);

		String[] sMessageFragment = sMessage.split("\n");

		String[] sTemp = sMessageFragment[0].split(":");
		this.lNewRowId = Integer.parseInt(sTemp[1]);
		Log.v("ActivityFairy", "ID:" + lNewRowId);

		sTemp = sMessageFragment[1].split(":");
		this.sContent = sTemp[1];
		Log.v("ActivityFairy", "Content:" + sContent);
		sTemp = sMessageFragment[2].split(":");
		this.sPlace = sTemp[1];
		Log.v("ActivityFairy", "Place:" + sPlace);
		sMessageFragment[3] = sMessageFragment[3].replace("时间:", "");
		String sDate = sMessageFragment[3].substring(0, sMessageFragment[3].indexOf("("));
		String[] dateTemp = sDate.split("-");

		this.iYear = Integer.parseInt(dateTemp[0]);
		this.iMonth = Integer.parseInt(dateTemp[1]) - 1;
		this.iDay = Integer.parseInt(dateTemp[2]);

		String sTime = sMessageFragment[3].substring(sMessageFragment[3].indexOf("(") + 1, sMessageFragment[3].indexOf(")"));

		dateTemp = sTime.split(":");

		this.iHour = Integer.parseInt(dateTemp[0]);
		this.iMinute = Integer.parseInt(dateTemp[1]);

		sTemp = sMessageFragment[4].split(":");
		this.iRingmode = getRingerMode(sTemp[1]);

		sTemp = sMessageFragment[5].split(":");
		this.bAlarm = "是".equals(sTemp[1]);

		sTemp = sMessageFragment[6].split(":");
		this.sRepeat = sTemp[1];

		// String[] sTemp = sMessage.split("\n活动:");
		// this.lNewRowId = Integer.parseInt(sTemp[0]);
		// String[] sTemp1 = sTemp[1].split("\n地点:");
		// this.sContent = sTemp1[0];
		// sTemp = null;
		// sTemp = sTemp1[1].split("\n时间:");
		// this.sPlace = sTemp[0];
		// sTemp1 = null;
		// sTemp1 = sTemp[1].split("\n模式:");
		// String[] sTemp2 = sTemp1[0].split("-");
		// this.iYear = Integer.parseInt(sTemp2[0]);
		// this.iMonth = Integer.parseInt(sTemp2[1]);
		// this.iDay = Integer.parseInt(sTemp2[2]);
		// sTemp = null;
		// sTemp2[3] = sTemp2[3].replace("(", "");
		// sTemp2[3] = sTemp2[3].replace(")", "");
		// sTemp = sTemp2[3].split(":");
		// this.iHour = Integer.parseInt(sTemp[0]);
		// this.iMinute = Integer.parseInt(sTemp[1]);
		// sTemp = null;
		// sTemp = sTemp1[1].split("\n闹铃:");
		// this.sRingmode = sTemp[0];
		// sTemp1 = null;
		// sTemp1 = sTemp[1].split("\n重复:");
		// this.sAlarm = sTemp1[0];
		// sTemp = null;
		// sTemp = sTemp1[1].split("\n参与人:");
		// this.sRepeat = sTemp[0];

	}

	private int getRingerMode(String sRingerMode) {
		int result = 0;
		if ("静音模式".equals(sRingerMode)) {
			result = 0;
		} else if ("振动模式".equals(sRingerMode)) {
			result = 1;
		} else if ("正常模式".equals(sRingerMode)) {
			result = 2;
		}
		return result;
	}

	private class GtalkServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppFacade = IXmppFacade.Stub.asInterface(service);

			try {
				mChatManager = mXmppFacade.getChatManager();

			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mXmppFacade = null;
			mChatManager = null;
		}

	};

}
